/**
 * 
 */
package cm.dpassyann.speedDating.ui.activity.connection.activity;

import roboguice.activity.RoboActivity;
import roboguice.activity.event.OnCreateEvent;
import roboguice.activity.event.OnResumeEvent;
import roboguice.activity.event.OnStopEvent;
import roboguice.event.EventManager;
import roboguice.event.Observes;
import roboguice.inject.ContextSingleton;
import roboguice.inject.InjectView;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageSwitcher;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import cm.dpassyann.speedDating.R;
import cm.dpassyann.speedDating.model.bean.user.User;
import cm.dpassyann.speedDating.model.dao.user.IUserDao;
import cm.dpassyann.speedDating.ui.activity.ILifeCycleActivity;
import cm.dpassyann.speedDating.ui.activity.connection.IConnectionActivity;
import cm.dpassyann.speedDating.ui.activity.connection.task.AnimImageTask;
import cm.dpassyann.speedDating.ui.activity.connection.task.ConnectionTask;
import cm.dpassyann.speedDating.ui.event.OnSpeedDatingExceptionEvent;
import cm.dpassyann.speedDating.util.SpeedDatingTransformationMethod;

import com.google.inject.Inject;

/**
 * @author deungoueyann
 *
 */
@ContextSingleton
public class ConnectionActivity extends RoboActivity implements IConnectionActivity, ILifeCycleActivity {

	/***********************************************************************************************************************
	 *                                           DÉCLARATION ET INJECTION DES VARIABLES                                    *
	 ***********************************************************************************************************************/
	@InjectView(R.id.connectionView) LinearLayout connectionView;
	@InjectView(R.id.pwdEditText) EditText pwdEditText;
	@InjectView(R.id.loginEditText) EditText loginEditText;
	@InjectView(R.id.menSwitcherImage) ImageSwitcher menSwitcherImage;
	@InjectView(R.id.womenSwitchImage) ImageSwitcher womenSwitchImage;

	@InjectView(R.id.facebookConnectionButton) Button facebookConnectionButton;
	@InjectView(R.id.newUserButton) Button newUserButton;
	@InjectView(R.id.connectionButton) Button connectionButton;
	@Inject AnimImageTask animImageTask;
	@Inject ConnectionTask connectionTask;
	
	private @Inject IUserDao userDao;

	private @Inject EventManager eventManager;

	private ProgressDialog dialog;


	/***********************************************************************************************************************
	 *                                             FONCTIONNEMENT GÉNÉRAL DE L'ACTIVITÉ                                    *
	 ***********************************************************************************************************************/
	/**
	 * 
	 * Méthode permettant de cacher le clavier lorsqu'on clique sur le container principal 
	 * @param v la vue qui déclenche cette evenement.
	 */
	public void onConnectionViewClick(View v){
		InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); 
		inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
	}

	public void animImageView() {
		menSwitcherImage.showNext();
		womenSwitchImage.showNext();
	}

	public void showProgress() {
		this.dialog = new ProgressDialog(this);

		this.dialog.getWindow().setBackgroundDrawable(new ColorDrawable(R.color.Chocolate));
		this.dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		this.dialog.setCancelable(false);
		this.dialog.setIndeterminate(true);
		this.dialog.setTitle("Connexion....");
		this.dialog.setMessage("Connexion en cours....");

		this.dialog.show();
	}

	private void stopImageAnimTask() {
		if(!animImageTask.isCancelled()){
			animImageTask.cancel(true);
		}
	}

	public void cancelProgress() {
		this.dialog.cancel();
		this.dialog = null;
	}
	public void isConnected(User user) {
		Toast.makeText(this, user.getEmail(), Toast.LENGTH_LONG).show();
	}
	/**
	 * Méthode permettant de lancer la connexion
	 * @param v le bouton sur lequel on click
	 */
	public void onConnectionClick(View v){
		stopImageAnimTask();
		String login = loginEditText.getText().toString();
		String password = pwdEditText.getText().toString();
		connectionTask = new ConnectionTask(this);
		connectionTask.execute(login,password);
	}
	
	public IUserDao getUserDao() {
		// TODO Auto-generated method stub
		return userDao;
	}

	public EventManager getEventManager() {
		// TODO Auto-generated method stub
		return eventManager;
	}

	/***********************************************************************************************************************
	 *                                           GESTION DES CONFIGURATION DE L'ACTIVITÉ                                   *
	 ***********************************************************************************************************************/

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		//on teste la configuration

		/**
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Log.w("****£"+StartActivity.class+"£*******","LANDSCAPE");
		} 

		else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			Log.w("****£"+StartActivity.class+"£*******","PORTAIT");
		}

		//*/

		//si besoin je peux forcer le refresh de la vue ici (locale|keyboardHidden|navigation|orientation|screenSize)
		//screensize aussi utilisé si on vérouille l'écran

		/** 
		setContentView(R.layout.main);
		//*/
	}

	@SuppressWarnings("deprecation")
	@Override
	public Object onRetainNonConfigurationInstance() {
		//méthode permettant de sauvegarder les configuration de la vue
		//Object o = getLastNonConfigurationInstance(); pour rétupérer les dernières config save
		return super.onRetainNonConfigurationInstance();
	}

	/************************************************************************************************************************************************************
	 *                                               CYCLE DE VIE DE L'ACTIVITÉ                                                                                 *
	 ************************************************************************************************************************************************************/

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		pwdEditText.setOnEditorActionListener(new OnEditorActionListener() {

			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

				boolean handled = false;
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					// Send the user message
					handled = true;
				}
				return handled;
			}
		});
	}

	public void onCreateActivity(@Observes OnCreateEvent onCreate) {
		setContentView(R.layout.connection);

		Animation in = AnimationUtils.loadAnimation(this,  android.R.anim.fade_in);
		Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
		in.setDuration(1500);
		out.setDuration(1500);

		womenSwitchImage.setInAnimation(in);
		womenSwitchImage.setOutAnimation(out);

		in = AnimationUtils.loadAnimation(this,  android.R.anim.slide_in_left);
		out = AnimationUtils.loadAnimation(this,  android.R.anim.slide_out_right);
		in.setDuration(1500);
		out.setDuration(1500);

		menSwitcherImage.setInAnimation(in);
		menSwitcherImage.setOutAnimation(out);

		//custom font
		Typeface tf = Typeface.createFromAsset(getAssets(),getString(R.string.font_path_achafsex));
		loginEditText.setTypeface(tf);
		pwdEditText.setTypeface(tf);


		facebookConnectionButton.setTypeface(tf);
		connectionButton.setTypeface(tf);
		newUserButton.setTypeface(tf);

		//set password transformation to DOT -> From HEART
		pwdEditText.setTransformationMethod(new SpeedDatingTransformationMethod());

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		connectionButton.setActivated(
				!"".equals(loginEditText.getText().toString()) &&
				!"".equals(pwdEditText.getText().toString())
				);

		animImageTask.execute();
	}

	public void onResumeActivity(@Observes OnResumeEvent onResume) {
		Log.w("****%$$%*******","Called doSomethingOnResume in onResume");
	}

	public void onStopActivity(@Observes OnStopEvent onStop) {
		Log.w("****%$$%*******","Called doSomethingonStop in onStop");
		animImageTask.cancel(true);
		if(connectionTask != null){
			connectionTask.cancel(true);
		}
	}

	public void onErrorActivity(@Observes OnSpeedDatingExceptionEvent event) {
		Log.w("****%$$%*******","Called doSomethingonErrorActivity in onError");
		Toast.makeText(this, event.getMessage(), Toast.LENGTH_LONG).show();
		cancelProgress();
		connectionTask.cancel(true);
		connectionTask = null;
		animImageTask = new AnimImageTask(this);
		animImageTask.execute();
	}
}
